package com.bwie.filter;

import com.alibaba.nacos.api.utils.StringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @Title:
 * @BelongProjecet month0617
 * @BelongPackage com.bwie.filter
 * @Description:
 * @Copyright 研发一部
 * @Author: Mr.yan
 * @Date: 2024/6/17 10:10
 * @Version V1.0
 */
@Configuration
public class MyFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取变量
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getPath().toString();
        System.out.println(url);
        String ip = request.getRemoteAddress().getAddress().toString();

        //2.设置白名单（不进行登录也可以操作）
        if (ip.contains("192.168.158.131")){
            System.out.println("放行");
            return chain.filter(exchange);
        }
        //放行获取验证码接口
        if (url.contains("/user/user/sendCode")){
            System.out.println("放行获取验证码接口");
            return chain.filter(exchange);
        }
        //放行登录接口
        if (url.contains("/user/user/userLogin")){
            System.out.println("放行登录接口");
            return chain.filter(exchange);
        }
        //放行忘记密码接口接口
        if (url.contains("/user/user/forgetPassword")){
            System.out.println("放行忘记密码接口");
            return chain.filter(exchange);
        }
        //放行图片上传接口

        //放行freeMaker接口

        //3.从请求头获取token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)){
            //未登录进行拦截
            System.out.println("未登录进行拦截");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //4.解析token，从缓存中获取redisToken
        Claims claims = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody();
        Integer userId = claims.get("id", Integer.class);
        String tokenKey = "token:id"+userId;
        String redisToken = stringRedisTemplate.opsForValue().get(tokenKey);
        //拦截异地登录
        if (!token.equals(redisToken)){
            System.out.println("异地登录进行拦截");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //5.自动续期
        if (stringRedisTemplate.getExpire(tokenKey, TimeUnit.MINUTES)<30){
            stringRedisTemplate.expire(tokenKey,30,TimeUnit.MINUTES);
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
